package com.llb666.shop.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.filter.ratelimit.RedisRateLimiter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;

import java.util.Objects;

/**
 * 限流.
 *
 * @author llb666
 */
@Configuration
public class RedisLimiterConfig {

    /**
     * 按IP来限流.
     * @return KeyResolver
     */
    @Bean(name = "ipKeyResolver")
    @Primary
    public KeyResolver remoteAddressKeyResolver() {
        return exchange -> Mono.just(
                Objects.requireNonNull(exchange.getRequest().getRemoteAddress()).getAddress().getHostAddress());
    }
}
